import { useEffect, useRef, useState } from 'react'
import Taro, { FC, useRouter } from "@tarojs/taro"
import { firstValueFrom, Subscription } from 'rxjs';
import { View, Text, Image, ScrollView } from "@tarojs/components"
import { AtTabs, AtTabsPane } from 'taro-ui'
import "taro-ui/dist/style/components/tabs.scss";
import { useRoomDataFacade } from '@/hooks/useRoomDataFacade';
import { useAuthFacade } from '@/hooks/useAuthFacade';
import { AnchorlatestRsp, GetAnchorDetailsRsp, LiveParams } from '@/models/response/userRsp';
import { formatTimes, numFormat } from '@/utils';
import { useRoomUiFacade } from '@/hooks/useRoomUiFacade';
import { TMPID_NOW, TMPID_READY } from '@/constants/user';
import CONFIG from "@/config";
import './index.scss'

//用户信息
export const UserInformation: FC = () => {
  //导入门面的所有元素作为页面绑定
  const [, , , , , , , , , roomRole,] = useRoomUiFacade();
  const [authFacade, loginStatus, userId, , , userInfo] = useAuthFacade();
  // const [authFacade, loginStatus, , , ,userId, userInfo] = useAuthFacade();
  const [roomFacade] = useRoomDataFacade();
  const [startedList, setStartedList] = useState([] as LiveParams[]) //直播中的数据
  const [noStartedList, setNoStartedList] = useState([] as LiveParams[]) //直播未开始的数据
  const [endedList, setEndedList] = useState([] as LiveParams[]) //直播已结束的数据
  const [DetailsList, setDetailsList] = useState({} as GetAnchorDetailsRsp) //主播详情信息
  const router = useRouter();
  const [navBarHeight, setNavBarHeight] = useState(0);//导航栏高度
  const [navHeight, setNavHeight] = useState(0);//胶囊高度
  const [topPadding, setTopPadding] = useState(0);//胶囊上边距
  const [navWidth, setNavWidth] = useState(0);//胶囊宽度 
  const [statusBarHeight, setstatusBarHeight] = useState(0);//状态栏高度 
  const [topMargin, setTopMargin] = useState(0);//高度差 
  const [isShow, setIsShow] = useState(false)  //显示、隐藏关注按钮
  const [cur, setcur] = useState(0) //默认页面初始值
  const userIdRef = useRef(router.params.userId || '');
  const [followStatus, setFollowStatus] = useState(router.params.isFollowed as unknown as boolean)
  //切换页面事件
  const handleClick = (value) => {
    setcur(value)
  }

  //返回上一页
  const goBack = () => {
    Taro.navigateBack({
      delta: 1
    })
  }

  //查看更多直播动态
  const goLiveTrends = () => {
    Taro.navigateTo({
      // url: '/pages/my/userLiveTrends/index'
      url: '/subPages/my/userLiveTrends/index'
    })
  }

  //查看我的关注
  const goMyAttention = () => {
    Taro.navigateTo({
      // url: '/pages/my/myAttention/index'
      url: '/subPages/my/myAttention/index'
    })
  }

  //查看我的粉丝
  const goMyFans = () => {
    Taro.navigateTo({
      // url: '/pages/my/myFans/index'
      url: '/subPages/my/myFans/index'
    })
  }


  //是否点击了关注
  const isClickAttention = () => {
    setFollowStatus(!followStatus)
    authFacade.addFollow(userIdRef.current, null as any, !followStatus)
  }

  const goToRoom = (roomId: string) => {
    console.log(1);

    Taro.navigateTo({
      url: `/pages/liveRoom/LiveDetails/index?roomId=${roomId}`
    })
  }
  const tabList = [{ title: '直播动态' }, { title: '个人信息' }]

  // 开播提醒
  const reservation = (e, roomId: string) => {
    // 阻止事件冒泡
    e.stopPropagation()
    Taro.requestSubscribeMessage({
      tmplIds: [TMPID_READY, TMPID_NOW],
      success: (res) => {
        console.log('方法返回', res,);
        const newTmpIds = [] as Array<string>
        // 筛选得出accept的id
        for (const tmplId in res) {
          if (res[tmplId] === 'accept') {
            newTmpIds.push(tmplId)
          }
        }
        console.log('取到的新数组', newTmpIds);
        firstValueFrom(authFacade.submitsubMsgIds(CONFIG.APPID, roomId, newTmpIds))
        // 用户取消或者设置不接收信息时返回
        if (res[TMPID_READY] === 'reject' && res[TMPID_NOW] === 'reject') {
          Taro.showToast({
            title: '操作失败',
            icon: 'none',
            duration: 2000
          })
        }
      },
      fail: (err) => {
        console.log('错误信息', err);
        if (err.errCode === 20004) {
          Taro.showToast({
            title: '用户关闭了消息通知，请在设置中打开',
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  }
  // 取得右上角胶囊高度，自定义标题与其对齐  
  useEffect(() => {
    Taro.getSystemInfo({
      success: function (res) {
        let myStatusBar = 0     // 状态栏高度
        let myCustomBar = 0  //导航栏高度
        let myNvaMartom = 0  //高度差
        let myNavHeight = 0   //胶囊高度
        let myNavWidth = 0   //胶囊宽度
        let myTopPadding = 0   //胶囊上边距 
        const custom = Taro.getMenuButtonBoundingClientRect();
        myStatusBar = res.statusBarHeight || 0;
        myNavHeight = custom.height;
        myNavWidth = custom.width;
        myTopPadding = custom.top;
        myNvaMartom = custom.top - myStatusBar;
        myCustomBar = (myNvaMartom * 2 + custom.height)
        setNavBarHeight(myCustomBar)
        setNavHeight(myNavHeight)
        setstatusBarHeight(myStatusBar)
        setTopMargin(myNvaMartom)
        setTopPadding(myTopPadding)
        setNavWidth(myNavWidth)
      }
    })
  }, [navBarHeight])

  useEffect(() => {
    if (userIdRef.current === '') return
    //注册并执行所有rxjs流
    const subscriptions: Subscription[] = [
      authFacade.getAnchorDetails(userIdRef.current)
        .subscribe(
          (res: GetAnchorDetailsRsp) => {
            setDetailsList(res);
          }
        )
    ];
    if (userId == userIdRef.current) {
      setIsShow(true)
    }
    //页面销毁时也销毁所有订阅，防止内存泄漏
    return () => { subscriptions.map(sub => sub.unsubscribe()) };
  }, []);

  useEffect(() => {
    if (userIdRef.current === '') return
    //注册并执行所有rxjs流
    const subscriptions: Subscription[] = [
      authFacade.getLatestShow('', userIdRef.current)
        .subscribe(
          (res: AnchorlatestRsp[]) => {
            res.map(item => {
              if (item.status == 'started') {
                const data = item.rooms.slice(0, 1)
                setStartedList(data)
              } else if (item.status == 'notStarted') {
                const data = item.rooms.slice(0, 2)
                setNoStartedList(data)
              } else {
                const data = item.rooms.slice(0, 2)
                setEndedList(data)
              }
            })
          }
        )
    ];
    //页面销毁时也销毁所有订阅，防止内存泄漏
    return () => { subscriptions.map(sub => sub.unsubscribe()) };
  }, []);

  return (
    <View className='index' >
      <View className='top' >
        <View className='position' style={{ height: navBarHeight + 'px', top: statusBarHeight + 'px' }}>
          <View className='navBox' style={{ height: navHeight + 'px', top: topMargin }}>
            <View className='orgName' >
              <Image className='goback' src='https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/goback.png' onClick={goBack}></Image>
              <View className='name'>主播信息</View>
            </View>
          </View>
        </View>
        <View className='top_main' style={{ marginTop: (statusBarHeight + navBarHeight) + 'px' }}>
          <View className='tx'><Image src={DetailsList.avatar} className='tx_img'></Image></View>
          <View className='border'>
            <View className='border-top'>
              <View className='nikname'> {DetailsList.realName}</View>
              {
                !isShow && (
                  <View className='edit' onClick={isClickAttention}>
                    <Image src={followStatus ? 'https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/correct.png' : 'https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/plus.png'} className='plus_img'></Image>
                    <View className='text'>{followStatus ? '已关注' : '关注'}</View>
                  </View>
                )
              }
            </View>
            <View className='info'>
              <View className='total' >总点赞数: {numFormat(DetailsList.likes)}</View>
              <View className='line'> </View>
              <View className='follow'>关注: {numFormat(DetailsList.follows)}</View>
              <View className='line'> </View>
              <View className='fans' >粉丝: {numFormat(DetailsList.following)}</View>
            </View>
          </View>
        </View>
      </View>
      <View className='main'>
        <AtTabs current={cur} tabList={tabList} onClick={handleClick.bind(this)}>
          <AtTabsPane current={cur} index={0}>
            <ScrollView scrollY className='liveStaus'>
              {
                startedList && startedList.length > 0 && startedList.map((item, index) => (
                  <View className='content1' key={index} onClick={() => goToRoom(item.roomId)}>
                    <View className='left'>
                      <View className='leftImg'>
                        <Image src={item.picUrl} className='left_img'></Image>
                        <View className='status'>
                          <Text> 直播中</Text>
                        </View>
                        <View className='play'>
                          <Image src='https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/play.png' className='play_img'></Image>
                        </View>
                      </View>
                      <View className='boxShadow'></View>
                    </View>
                    <View className='right'>
                      <View className='title'>
                        <Text>{item.roomName}</Text>
                      </View>
                      <View className='time'>
                        <Text>正在直播中</Text>
                      </View>
                    </View>
                  </View>
                ))
              }

              {/* 未开始直播 */}
              {
                noStartedList && noStartedList.length > 0 && (
                  <View className='notStarted' >
                    <View className='topTitle'>
                      <View className='Title'>未开始直播</View>
                      <View className='more' onClick={goLiveTrends}>查看更多</View>
                    </View>
                    {
                      noStartedList.map((item, index) => (
                        <View className='content2' key={index} onClick={() => goToRoom(item.roomId)}>
                          <View className='left'>
                            <View className='leftImg'>
                              <Image src={item.picUrl} className='left_img'></Image>
                              <View className='status'>
                                <Text> 待开始</Text>
                              </View>
                              <View className='play'>
                                <Image src='https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/play.png' className='play_img'></Image>
                              </View>
                            </View>
                            <View className='boxShadow'></View>
                          </View>
                          <View className='right'>
                            <View className='title'>
                              <Text>{item.roomName}</Text>
                            </View>
                            <View className='bottom'>
                              <View className='time'>开播时间: {formatTimes(new Date(item.startTime))}</View>
                              <View className='butn' onClick={(e) => { reservation(e, item.roomId) }}>开播提醒</View>
                            </View>
                          </View>
                        </View>
                      ))
                    }
                  </View>
                )
              }
              {/* 已结束直播 */}

              {
                endedList && endedList.length > 0 && (
                  <View className='ended'>
                    <View className='topTitle'>
                      <View className='Title'>已结束直播</View>
                      <View className='more' onClick={goLiveTrends}>查看更多</View>
                    </View>
                    {
                      endedList.map((item, index) => (
                        <View className='content3' key={index} onClick={() => goToRoom(item.roomId)}>
                          <View className='left'>
                            <View className='leftImg'>
                              <Image src={item.picUrl} className='left_img'></Image>
                              <View className='status'>
                                <Text> 看回放</Text>
                              </View>
                              <View className='play'>
                                <Image src='https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/play.png' className='play_img'></Image>
                              </View>
                            </View>
                            <View className='boxShadow'></View>
                          </View>
                          <View className='right'>
                            <View className='title'>
                              <Text>{item.roomName}</Text>
                            </View>
                            <View className='time'>
                              <Text>结束时间: {formatTimes(new Date(item.endTime))}</Text>
                            </View>
                          </View>
                        </View>
                      ))
                    }
                  </View>
                )
              }
            </ScrollView>
          </AtTabsPane>
          <AtTabsPane current={cur} index={1} >
            <View className='content'>
              <View className='box1'>
                <View className='sex'><Text>性别</Text></View>
                <View className='sexs'>{DetailsList.sexual === 1 ? '男' : '女'}</View>
              </View>
              <View className='box1'>
                <View className='useVer'><Text>个人认证</Text></View>
                <View className='verify'>已认证</View>
              </View>
              <View className='box1'>
                <View className='org'><Text>所属机构</Text></View>
                <View className='orgnation'>{DetailsList.orgName}</View>
              </View>
            </View>
            <View className='tip' >
              <Text>个人简介</Text>
            </View>
            <View className='tip_ct'>
              <Text>{DetailsList.desc}</Text>
            </View>
          </AtTabsPane>
        </AtTabs>
      </View>
    </View>
  )
}
export default UserInformation